<template>
  <div class="create-issue">
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/issues' }">问题管理</el-breadcrumb-item>
        <el-breadcrumb-item>报告问题</el-breadcrumb-item>
      </el-breadcrumb>
      <h1>报告问题</h1>
    </div>

    <div class="content-container">
      <el-card>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          v-loading="loading"
        >
          <el-form-item label="问题标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入问题标题" />
          </el-form-item>

          <el-form-item label="问题描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="6"
              placeholder="请详细描述问题的具体情况、重现步骤等"
            />
          </el-form-item>

          <el-form-item label="关联项目" prop="projectId">
            <el-select v-model="form.projectId" placeholder="请选择关联项目">
              <el-option
                v-for="project in projects"
                :key="project.id"
                :label="project.name"
                :value="project.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="关联任务" prop="taskId">
            <el-select v-model="form.taskId" placeholder="请选择关联任务（可选）" clearable>
              <el-option
                v-for="task in filteredTasks"
                :key="task.id"
                :label="task.title"
                :value="task.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="问题类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择问题类型">
              <el-option label="功能缺陷" value="bug" />
              <el-option label="功能需求" value="feature" />
              <el-option label="性能问题" value="performance" />
              <el-option label="用户体验" value="ux" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>

          <el-form-item label="优先级" prop="priority">
            <el-select v-model="form.priority" placeholder="请选择优先级">
              <el-option label="低" value="low" />
              <el-option label="中" value="medium" />
              <el-option label="高" value="high" />
              <el-option label="紧急" value="urgent" />
            </el-select>
          </el-form-item>

          <el-form-item label="指派给" prop="assigneeId">
            <el-select v-model="form.assigneeId" placeholder="请选择处理人（可选）" clearable>
              <el-option
                v-for="user in users"
                :key="user.id"
                :label="user.realName"
                :value="user.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="截止日期" prop="dueDate">
            <el-date-picker
              v-model="form.dueDate"
              type="date"
              placeholder="选择截止日期（可选）"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">
              提交问题
            </el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
// import { issueApi } from '@/api/issue'
// import { projectApi } from '@/api/project'
// import { taskApi } from '@/api/task'
// import { userApi } from '@/api/user'

const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
const submitting = ref(false)
const projects = ref<any[]>([])
const tasks = ref<any[]>([])
const users = ref<any[]>([])

const form = reactive({
  title: '',
  description: '',
  projectId: '',
  taskId: '',
  type: 'bug',
  priority: 'medium',
  assigneeId: '',
  dueDate: ''
})

const rules: FormRules = {
  title: [
    { required: true, message: '请输入问题标题', trigger: 'blur' },
    { min: 2, max: 100, message: '问题标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入问题描述', trigger: 'blur' },
    { min: 10, message: '问题描述至少10个字符', trigger: 'blur' }
  ],
  projectId: [
    { required: true, message: '请选择关联项目', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择问题类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

// 根据选择的项目过滤任务
const filteredTasks = computed(() => {
  if (!form.projectId) return []
  return tasks.value.filter((task: any) => task.projectId === form.projectId)
})

const loadProjects = async () => {
  try {
    // 模拟项目数据
    projects.value = [
      { id: '1', name: '电商平台重构项目' },
      { id: '2', name: '移动端APP开发' },
      { id: '3', name: '数据分析平台' }
    ] as any
  } catch (error) {
    console.error('加载项目列表失败:', error)
  }
}

const loadTasks = async () => {
  try {
    // 模拟任务数据
    tasks.value = [
      { id: '1', title: '用户登录功能开发', projectId: '1' },
      { id: '2', title: '商品管理模块', projectId: '1' },
      { id: '3', title: 'UI界面设计', projectId: '2' },
      { id: '4', title: '数据可视化组件', projectId: '3' }
    ] as any
  } catch (error) {
    console.error('加载任务列表失败:', error)
  }
}

const loadUsers = async () => {
  try {
    // 模拟用户数据
    users.value = [
      { id: '1', realName: '张三' },
      { id: '2', realName: '李四' },
      { id: '3', realName: '王五' },
      { id: '4', realName: '赵六' }
    ] as any
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 这里应该调用真实的API
    // const result = await issueApi.createIssue(form)
    
    ElMessage.success('问题提交成功')
    router.push('/issues')
  } catch (error) {
    console.error('提交问题失败:', error)
    ElMessage.error('提交问题失败')
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  ElMessageBox.confirm(
    '确定要取消提交吗？已填写的内容将会丢失。',
    '确认取消',
    {
      confirmButtonText: '确定',
      cancelButtonText: '继续填写',
      type: 'warning'
    }
  ).then(() => {
    router.push('/issues')
  }).catch(() => {
    // 用户取消
  })
}

// 监听项目变化，清空任务选择
// const handleProjectChange = () => {
//   form.taskId = ''
// }

onMounted(() => {
  loadProjects()
  loadTasks()
  loadUsers()
})
</script>

<style scoped>
.create-issue {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 10px 0;
  font-size: 24px;
  font-weight: 500;
  color: #303133;
}

.content-container {
  max-width: 800px;
}

.el-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input,
.el-select,
.el-date-picker {
  width: 100%;
}

.el-textarea {
  width: 100%;
}
</style>